package my.study.netty;

import com.imooc.netty.samples.$998.client.mock.MockClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * 参考com.imooc.netty.samples.$998.client.MahjongClient
 * (最简单的实现,在idea中按ctrl+n进行搜索"MahjongClient"类,可以发现有好几个实现版本)
 * <p>
 * 注:配套服务端类StudyNettyServer
 * <p>
 * 测试:先运行StudyNettyServer、再运行该类
 */
public class StudyNettyClient {
    static final int PORT = Integer.parseInt(System.getProperty("port", "8088"));

    public static void main(String[] args) {

        // NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            // 注:下面的可以连续打点调用,如  bootstrap.group(workerGroup).channel()等
            bootstrap.group(workerGroup);
            // bootstrap.channel(NioSocketChannel.class);
            bootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // pipeline.addLast(new LoggingHandler(LogLevel.INFO)); // 打印日志
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new EchoClientHandler());
                }
            });

            // 连接到服务器
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(PORT)).sync();
            System.out.println("已连接到服务器...");


            System.out.println("请输入任意名字,然后观察client和server的打印");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String content = scanner.nextLine();
                future.channel().writeAndFlush(content);
            }

            // future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}